<?php

namespace App\Jobs;

use App\Models\Prize;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 抽奖异步任务
 * 
 * 处理抽奖后的异步操作：
 * 1. 更新数据库中的奖品库存
 * 2. 记录中奖信息
 * 3. 更新统计数据
 */
class LotteryDrawTask implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    private $prizeId;
    private $userId;
    private $drawTime;

    /**
     * 创建任务实例
     *
     * @param int $prizeId 奖品ID
     * @param int $userId 用户ID
     * @param string $drawTime 抽奖时间
     */
    public function __construct(int $prizeId, int $userId, string $drawTime)
    {
        $this->prizeId = $prizeId;
        $this->userId = $userId;
        $this->drawTime = $drawTime;
    }

    /**
     * 执行任务
     *
     * @return void
     */
    public function handle()
    {
        Log::info('开始处理抽奖异步任务', [
            'prize_id' => $this->prizeId,
            'user_id' => $this->userId,
            'draw_time' => $this->drawTime
        ]);

        try {
            DB::transaction(function() {
                // 1. 更新奖品库存
                Prize::where('id', $this->prizeId)->update([
                    'stock' => DB::raw('stock - 1')
                ]);

                // 2. 记录中奖记录
                DB::table('prize_records')->insert([
                    'prize_id' => $this->prizeId,
                    'user_id' => $this->userId,
                    'created_at' => $this->drawTime,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                // 3. 更新统计数据（如果有统计表的话）
                // DB::table('prize_statistics')
                //     ->where('prize_id', $this->prizeId)
                //     ->increment('win_count');

                Log::info('抽奖异步任务处理成功', [
                    'prize_id' => $this->prizeId,
                    'user_id' => $this->userId
                ]);
            });
        } catch (\Exception $e) {
            Log::error('抽奖异步任务处理失败', [
                'prize_id' => $this->prizeId,
                'user_id' => $this->userId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            // 失败后延迟30秒重试
            $this->release(30);
        }
    }
} 